package com.wing.order.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wing.cabinet.model.entity.*;
import com.wing.cabinet.model.request.CellInventoryInoutDetailForm;
import com.wing.cabinet.model.request.UseInventoryInoutDetailForm;
import com.wing.cabinet.model.request.UseInventoryInoutForm;
import com.wing.cabinet.model.response.UseInventoryUserVO;
import com.wing.cabinet.service.*;
import com.wing.common.exception.BusinessException;
import com.wing.common.utils.JsonResult;
import com.wing.order.dao.OldNewOrderDao;
import com.wing.order.model.entity.OldNewOrder;
import com.wing.order.model.request.OldNewOrderForm;
import com.wing.order.model.response.OldNewOrderVO;
import com.wing.product.model.response.ProductDetailVO;
import com.wing.product.service.ProductDetailService;
import com.wing.setting.model.entity.SystemRuleInfo;
import com.wing.setting.service.SystemRuleInfoService;
import com.wing.user.feign.UserClient;
import com.wing.user.model.response.DepartmentVO;
import com.wing.web.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 以旧换新(存旧刀，领新刀)-ServiceImpl
 *
 * @author
 */
@Service
@Slf4j
public class OldNewOrderServiceImpl extends ServiceImpl<OldNewOrderDao, OldNewOrder> implements OldNewOrderService {

    @Autowired
    private StorageInventoryInoutDetailService storageInventoryInoutDetailService;

    @Autowired
    private CellInventoryInoutDetailService cellInventoryInoutDetailService;

    @Autowired
    private DynamicService dynamicService;

    @Autowired
    private UseInventoryUserService useInventoryUserService;

    @Autowired
    private CellInventoryInoutService cellInventoryInoutService;

    @Autowired
    private ProductDetailService productDetailService;

    @Autowired
    private SystemRuleInfoService systemRuleInfoService;
    @Autowired
    private UserClient userClient;

    @Autowired
    private UseInventoryKnifeService useInventoryKnifeService;

    @Override
    public int add(OldNewOrderForm oldNewOrderForm) {

        //校验

        OldNewOrder oldNewOrder =new OldNewOrder();
        CopyOptions copyOptions = CopyOptions.create()
        .setEditable(OldNewOrder.class)
        .setIgnoreError(true)
        .setIgnoreNullValue(true);
        BeanUtil.copyProperties(oldNewOrderForm, oldNewOrder, copyOptions);

        return baseMapper.insert(oldNewOrder);
    }

    @Override
    public List<OldNewOrderVO> list4app(Map<String, Object> params) {
        return baseMapper.list4app(params);
    }

    @Override
    public Page<OldNewOrderVO> pageList4app(Page page, Map<String, Object> params) {
        List<OldNewOrderVO> list = baseMapper.list4app(page, params);
        for(OldNewOrderVO item : list){
            JsonResult<DepartmentVO> jsonResult = userClient.getDepartmentVOById(item.getDepartmentId());
            if(null != jsonResult && jsonResult.getData() != null) {
                item.setCostCenter(jsonResult.getData().getCostCenter());
            }
        }
        page.setRecords(list);
        return page;
    }

    @Override
    public OldNewOrderVO get4appById(Long id) {
        return baseMapper.get4appById(id);
    }

    @Override
    @Transactional
    public JsonResult<CellInventoryInout> inventoryInOut(UseInventoryInoutForm useInventoryInoutForm) {
        if (CollectionUtil.isEmpty(useInventoryInoutForm.getCellDetailList())){
            throw new BusinessException("缺少领新数据参数");
        }
        if (CollectionUtil.isEmpty(useInventoryInoutForm.getStorageDetailList())){
            throw new BusinessException("缺少存刀数据参数");
        }
        if (StringUtils.isBlank(useInventoryInoutForm.getDeviceCode())){
            useInventoryInoutForm.setDeviceCode(useInventoryInoutForm.getStorageDetailList().get(0).getDeviceCode());
        }
        String departmentName=JwtUtils.getDepartmentName();
        String roleName=JwtUtils.getRoleName();
//        useInventoryInoutForm.getCellDetailList().get(0).setWorkOrderId(useInventoryInoutForm.getWorkOrderId());
//        useInventoryInoutForm.getStorageDetailList().get(0).setWorkOrderId(useInventoryInoutForm.getWorkOrderId());
//        useInventoryInoutForm.getStorageDetailList().get(0).setUseTime(useInventoryInoutForm.getUseTime());
//        useInventoryInoutForm.getStorageDetailList().get(0).setSpaceType(useInventoryInoutForm.getSpaceType());
        if (StringUtils.isBlank(useInventoryInoutForm.getStorageDetailList().get(0).getSkuCode())){
            useInventoryInoutForm.getStorageDetailList().get(0).setSkuCode(useInventoryInoutForm.getCellDetailList().get(0).getSkuCode());
        }
        if (useInventoryInoutForm.getStorageDetailList().get(0).getQuantity()==null||useInventoryInoutForm.getStorageDetailList().get(0).getQuantity()==0){
            useInventoryInoutForm.getStorageDetailList().get(0).setQuantity(1);
        }
        Long oldCellInventoryInoutId=null;
        UseInventoryUserVO useInventoryUserVO = null;
        UseInventoryKnife useInventoryKnife = useInventoryKnifeService.getById(useInventoryInoutForm.getStorageDetailList().get(0).getId());
        if(null != useInventoryKnife) {
            useInventoryUserVO = useInventoryUserService.get4appById(useInventoryKnife.getUseInventoryUserId());
            if (useInventoryUserVO != null) {
                oldCellInventoryInoutId = useInventoryUserVO.getCellInventoryInoutId();
            }
        }
        StorageInventoryInout storageInventoryInout=null;
//        CabinetCargoSpace.SpaceType spaceType=useInventoryInoutForm.getStorageDetailList().get(0).getSpaceType();
        CabinetCargoSpace.SpaceType spaceType=useInventoryInoutForm.getSpaceType();
        if (CabinetCargoSpace.SpaceType.temp.equals(spaceType)){
            storageInventoryInout=storageInventoryInoutDetailService.inventoryIn(useInventoryInoutForm.getStorageDetailList(), StorageInventoryInout.BusinessType.temp,useInventoryInoutForm.getDeviceCode(),StorageInventoryInout.BusinessDetailType.tempInByOldNew,useInventoryInoutForm.getRemark());
        }else if(CabinetCargoSpace.SpaceType.repair.equals(spaceType)){
            storageInventoryInout=storageInventoryInoutDetailService.inventoryIn(useInventoryInoutForm.getStorageDetailList(), StorageInventoryInout.BusinessType.repair,useInventoryInoutForm.getDeviceCode(),StorageInventoryInout.BusinessDetailType.repairInByOldNew,useInventoryInoutForm.getRemark());
        }else if(CabinetCargoSpace.SpaceType.recycle.equals(spaceType)){
            storageInventoryInout=storageInventoryInoutDetailService.inventoryIn(useInventoryInoutForm.getStorageDetailList(), StorageInventoryInout.BusinessType.recycle,useInventoryInoutForm.getDeviceCode(),StorageInventoryInout.BusinessDetailType.recycleInByOldNew,useInventoryInoutForm.getRemark());
        }else{
            throw new BusinessException("存贮参数异常");
        }
        CellInventoryInout cellInventoryInout=new CellInventoryInout();
        for(CellInventoryInoutDetailForm e : useInventoryInoutForm.getCellDetailList()){
        //useInventoryInoutForm.getCellDetailList().forEach(e->{
            if (StringUtils.isBlank(e.getDeviceCode())){
                e.setDeviceCode(useInventoryInoutForm.getStorageDetailList().get(0).getDeviceCode());
            }
            if(null != useInventoryUserVO) {
                e.setWorkOrderId(useInventoryUserVO.getWorkOrderId());
            }
        //});
        }
        if (CellInventoryInoutDetailForm.CabType.saleCab.equals(useInventoryInoutForm.getCellDetailList().get(0).getCabType())){
            cellInventoryInout=cellInventoryInoutDetailService.inventoryOut(useInventoryInoutForm.getCellDetailList(),useInventoryInoutForm.getDeviceCode(),CellInventoryInout.BusinessType.cellCabOutByOldNew, UseInventoryInout.BusinessType.cellCabOutByOldNew,null,null,useInventoryInoutForm.getUuid());
        }else{
            List<UseInventoryInoutDetailForm> useInventoryInoutDetailFormsList=new ArrayList<>();
            useInventoryInoutForm.getCellDetailList().forEach(e->{
                UseInventoryInoutDetailForm useInventoryInoutDetailForm=new UseInventoryInoutDetailForm();
                BeanUtils.copyProperties(e,useInventoryInoutDetailForm);
                useInventoryInoutDetailFormsList.add(useInventoryInoutDetailForm);
            });
            StorageInventoryInout storageInventoryInout2=storageInventoryInoutDetailService.inventoryOut(useInventoryInoutDetailFormsList, StorageInventoryInout.BusinessType.exhibit,useInventoryInoutForm.getDeviceCode(),StorageInventoryInout.BusinessDetailType.newOut,UseInventoryInout.BusinessType.newOut);
            BeanUtils.copyProperties(storageInventoryInout2,cellInventoryInout);
        }


        ProductDetailVO productDetailVO = productDetailService.getProductDetailBySkuCode(useInventoryInoutForm.getCellDetailList().get(0).getSkuCode());
        SystemRuleInfo systemRuleInfo = systemRuleInfoService.getOne(new QueryWrapper<SystemRuleInfo>());
        boolean lifeFlag = false;
        if (systemRuleInfo != null) {
            lifeFlag = systemRuleInfo.getLifeFlag();
        }
        if (lifeFlag && productDetailVO != null && productDetailVO.getLifeSpan() != null && productDetailVO.getLifeSpan() != 0 ) {
            cellInventoryInout.setSettingTime(productDetailVO.getLifeSpan());
            cellInventoryInout.setRemainingTime(productDetailVO.getLifeSpan());
            cellInventoryInout.setLifeUnit(productDetailVO.getLifeUnit());
        }
        cellInventoryInout.setDeviceCode(useInventoryInoutForm.getDeviceCode());//添加机台
        OldNewOrder oldNewOrder=new OldNewOrder();
        Long creator= JwtUtils.getLoginUserId();
        String creatorName=JwtUtils.getLoginUsername();
        String enterpriseCode=JwtUtils.getEnterpriseCode();
        String code=dynamicService.getDayNextCode("ord_order_receive");
        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyyMMdd");
        String day=simpleDateFormat.format(new Date());
        oldNewOrder.setDay(Integer.valueOf(day));
        oldNewOrder.setNo(Integer.valueOf(code));
        oldNewOrder.setCode("ON-"+day+"-"+code);
        oldNewOrder.setCreator(creator);
        oldNewOrder.setCreatorName(creatorName);
        oldNewOrder.setOldCellInventoryInoutId(oldCellInventoryInoutId);
        oldNewOrder.setNewCellInventoryInoutId(cellInventoryInout.getId());
        oldNewOrder.setStorageInventoryInoutId(storageInventoryInout.getId());
        oldNewOrder.setSkuCode(useInventoryInoutForm.getCellDetailList().get(0).getSkuCode());
        oldNewOrder.setDeviceCode(useInventoryInoutForm.getCellDetailList().get(0).getDeviceCode());
        oldNewOrder.setWorkOrderId(useInventoryInoutForm.getWorkOrderId());
        oldNewOrder.setEnterpriseCode(enterpriseCode);
        oldNewOrder.setDepartmentName(departmentName);
        oldNewOrder.setDepartmentId(JwtUtils.getDepartmentId());
        oldNewOrder.setRoleName(roleName);
        oldNewOrder.setRemark(useInventoryInoutForm.getRemark());
        oldNewOrder.setDeviceCode(useInventoryInoutForm.getDeviceCode());//添加机台
        baseMapper.insert(oldNewOrder);
        return JsonResult.success(cellInventoryInout);
    }


}
